<?php
namespace Admin\Model;
use Think\Model;

class ConfigModel extends Model {
	protected $_validate = array(
			array('name','require','配置标识必须填写！'),
			array('name','','配置标识已经存在！',0,'unique'),
			array('title','require','配置标题必须填写！'),
			array('value','require','配置内容必须填写！'),
	);
	protected $_auto = array(
			array('name', 'strtoupper', self::MODEL_BOTH, 'function'),
			array('create_time','time',1,'function'),
			array('update_time','time',2,'function'),
			array('status',1,1)
	);
	
	/**
	 * 获取配置列表
	 * @return array 配置数组
	 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
	 */
	public function lists(){
		$map    = array('status' => 1);
		$data   = $this->where($map)->field('type,name,value')->select();
	
		$config = array();
		if($data && is_array($data)){
			foreach ($data as $value) {
				$config[$value['name']] = $this->parse($value['type'], $value['value']);
			}
		}
		return $config;
	}
	
	/**
	 * 根据配置类型解析配置
	 * @param  integer $type  配置类型
	 * @param  string  $value 配置值
	 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
	 */
	private function parse($type, $value){
		switch ($type) {
			case 3: //解析数组
				$array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
				if(strpos($value,':')){
					$value  = array();
					foreach ($array as $val) {
						list($k, $v) = explode(':', $val);
						$value[$k]   = $v;
					}
				}else{
					$value =    $array;
				}
				break;
		}
		return $value;
	}
	
}